package com.taysear.bus;

import java.util.List;

import com.taysear.bus.util.Constants;
import com.taysear.domain.Permission;
import com.vaadin.ui.Component;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.MenuBar.MenuItem;

/**
 * <code>MenuBar</code> is used to create the application menu bar.
 * 
 * @author Abdullahi
 */
@SuppressWarnings("serial")
public class MenuBar extends HorizontalLayout  {
	
	final com.vaadin.ui.MenuBar menubar = new com.vaadin.ui.MenuBar();
	
	
	public MenuBar(List menus) {
	    MenuItem mymenu = null;
	    for (Object object : menus) {
			Permission permission = (Permission) object;
			if (permission.getPermissionId().intValue() == permission.getParent().intValue()) {
		    	mymenu = menubar.addItem(permission.getName(), null);
		    } else {
		    	 MenuItem sub = mymenu.addItem(permission.getName(), null);
		    	 sub.setDescription(permission.getDescription());
		    	 sub.setCommand(new Command(permission.getCommand()));
		    }
		}
		addComponent(menubar);
	}
	
	private class Command implements com.vaadin.ui.MenuBar.Command {
		String command = null;
		
		public Command(String command) {
			this.command = command;
		}

		@Override
		public void menuSelected(MenuItem selectedItem) {
			BusApplication app = (BusApplication) getApplication();
			// Create objects from the menuUrl string
			try {
				Class cls = Class.forName("com.taysear.bus." + command);
				Object object = cls.newInstance();
				app.getMainLayout().getCenter().removeAllComponents();
				app.getMainLayout().getCenter().addComponent((Component) object);
				
			} catch (ClassNotFoundException e) {
				//app.showErrorNotification(Constants.MN_EMPTY_MENU);
				app.getMainLayout().getCenter().removeAllComponents();
				System.out.println(e.getMessage() +" does not exist");
			} catch (InstantiationException e) {
				System.out.println(e.getMessage());
			} catch (IllegalAccessException e) {
				System.out.println(e.getMessage());
			}
		}
		
	}
}
